import {Button, Input, Modal, Upload, Divider, Image, message, Select} from 'antd';
import React, {useState, useRef, useEffect} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import {purchaseList, getPurchaseDetail, addDriverDetails,delPayFile,delDriver,changeMoney} from './service';
import defaultSetting from '@/../config/defaultSettings';
import Access from '@/components/Access/Access';

import CreateForm from "./components/CreateForm";
import "./index.css";

import {
  PlusOutlined
} from '@ant-design/icons';

import styles from "@/global.less";
import {saveFileAs} from "@/utils/utils";


const {baseUrl} = defaultSetting;
const TableList = (props) => {
  const actionRef = useRef();
  const [count, setCount] = useState();
  const [purchaseDetail, handlePurchaseDetail] = useState(false);
  const [purchaseDetails, handlePurchaseDetails] = useState(false);
  const [record, setRecord] = useState({});
  const [details, setDetails] = useState({});
  const [mySelectedRowKeys, handleMySelectedRowKeys] = useState([]);
  const [purchaseOutDetail, handlePurchaseOutDetail] = useState(false);
  const [driverStockLoading, handleDriverStockLoading] = useState(false);

  const [fileList, handleFileList] = useState([]);
  useEffect(() => {

  }, []);
  let cancleRowKeys = [];
  const onSelect = (record, selected) => {
    if (!selected) {
      cancleRowKeys = [record.id];
    }
  };
  const onMulSelect = (selected, selectedRows, changeRows) => {
    if (!selected) {
      cancleRowKeys = changeRows.map((item) => item.id);
    }
  };
  const onChange = (selectedRowKeys, selectedRows) => {

    if (cancleRowKeys.length) {
      const keys = mySelectedRowKeys.filter((item) => !cancleRowKeys.includes(item));
      handleMySelectedRowKeys(keys);
      cancleRowKeys = [];
    } else {
      handleMySelectedRowKeys([...new Set(mySelectedRowKeys.concat(selectedRowKeys))]);
    }

  };
  const simpleColumns = [
    {
      title: '客户名/电话',
      dataIndex: 'searchValue',
      hideInTable:true
    },
    {
      title: '申请人',
      dataIndex: 'seller',
      hideInSearch: true,
    },
    {
      title: '客户名称',
      dataIndex: 'name',
      hideInSearch: true,
    },
    {
      title: '联系人',
      dataIndex: 'user',
      hideInSearch: true,
    },
    {
      title: '客户电话',
      dataIndex: 'tel',
      hideInSearch: true,
    },
    {
      title: '采购时间',
      dataIndex: 'createTime',
      hideInSearch: true,
    },
    {
      title: '付款类型',
      dataIndex: 'payType',
      hideInSearch: true,
      valueEnum: {
        0: {
          text: '预付货款',
          status: 'Processing',
        },
        1: {
          text: '后付款',
          status: 'Error',
        },
        2: {
          text: '账期付款',
          status: 'Error',
        },
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInSearch: true,
      valueEnum: {
        0: {
          text: '预付审批中',
          status: 'Error',
        },
        1: {
          text: '采购审批中',
          status: 'Error',
        },
        2: {
          text: '待入库',
          status: 'Error',
        },
        3: {
          text: '入库审批中',
          status: 'Error',
        },
        4: {
          text: '部分入库',
          status: 'Processing',
        },
        5: {
          text: '入库已完成',
          status: 'Processing',
        },
        6: {
          text: '已退货',
          status: 'Error',
        },
        8: {
          text: '付款中',
          status: 'Error',
        },
        9: {
          text: '已完成',
          status: 'Success',
        },
        99: {
          text: '已驳回',
          status: 'Error',
        },
      },
    },
  ];

  const columns = simpleColumns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      render: (_, item) => {
        return (
          <>
            <div style={{
              display: "flex",
              overflow: "hidden"
            }}>
              <Access accessKey={"@stuff_inStock"}>
                <Button
                  danger
                  type="primary"
                  onClick={() => {
                    setRecord(item);
                    let params = {
                      id: item.id
                    };
                    getPurchaseDetail(params).then(res => {
                      setDetails(res.data);
                      handleFileList(res.data.imgs.map(img=>{
                        return {
                          uid:img.id,
                          status: 'done',
                          url:img.img
                        }
                      }));
                      handleMySelectedRowKeys(res.data.details.map(detail=>detail.id));
                      handlePurchaseOutDetail(true);
                    });

                  }}
                >
                  办理入库
                </Button>
              </Access>


            </div>
          </>
        );
      },
    },
  ]);


  const showConfirm = (record)=>{
    Modal.success({
      title: '注意',
      okText:'确定',
      content: '确认要修改'+record.title+'的入库数量为'+record.tempStock+'吗?',
      onOk() {

      },
    });
  };
  const detailColumns = [
    {
      title: '商品',
      dataIndex: 'title',
      hideInSearch: true,
      width: 10,
    },
    {
      title: '条码',
      dataIndex: 'barCode',
      hideInSearch: true,
      width: 10,
    },
    {
      title: '规格',
      dataIndex: 'spec',
      hideInSearch: true,
      width: 10,
    },
    {
      title: '单位',
      dataIndex: 'unit',
      hideInSearch: true,
      width: 10,
    },
    {
      title: '采购数量',
      dataIndex: 'value',
      hideInSearch: true,
      width: 10,
    },
    {
      title: '价格',
      dataIndex: 'dataPrice',
      hideInSearch: true,
      width: 10,
    },
    {
      title: '入库数量',
      hideInSearch:true,
      dataIndex: 'inStock',
      width: 10,
      render: (dom, record) => {
        let flag = false;
        let curStock = record.value - (record.inStock?record.inStock:0);
        return <Input
          disabled={curStock <= 0}
          placeholder={curStock}
          onChange={(e) => {
            let inpStock = e.target.value;
            if (inpStock > curStock) {
              message.warn("入库数量已超过未入库数量!");
            }
            record.tempStock = e.target.value;
            flag = true;
          }
          }
          onPressEnter={()=>{
            if (record.tempStock && flag) {
              flag = false;
              showConfirm(record);
            }
          }
          }
          onBlur={()=>{
            if(record.tempStock && flag){
              flag = false;
              showConfirm(record,this)
            }
          }
          }
        />;
      },
    },
  ];

  const detailShowColumns = [
    {
      title: '商品',
      dataIndex: 'goodsName',
      hideInSearch: true,
    },
    {
      title: '条码',
      dataIndex: 'barCode',
      hideInSearch: true,
    },
    {
      title: '采购数量',
      dataIndex: 'purchaseNumber',
      hideInSearch: true,
    },
    {
      title: '库存',
      dataIndex: 'sysStock',
      hideInSearch: true,
    },
    {
      title: '价格',
      dataIndex: 'goodsPrice',
      hideInSearch: true,
    },
  ];

  const driverBaseColumns = [
    {
      title: '运费',
      dataIndex: 'carMoney',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '运费为必填项',
          },
        ],
      },
    },
    {
      title: '结算账号',
      dataIndex: 'payment',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '司机结算账号为必填项',
          },
        ],
      },
    },
    {
      title: '开户行',
      dataIndex: 'bank',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '司机结算账号开户行为必填项',
          },
        ],
      },
    },
    {
      title: '司机',
      dataIndex: 'driver',
      valueType: 'text',
    },
    {
      title: '车牌',
      dataIndex: 'carNum',
      valueType: 'text',
    },
    {
      title: '电话',
      dataIndex: 'driverTel',
      valueType: 'text',
    },
    {
      title: '身份证',
      dataIndex: 'driverCard',
      valueType: 'text',
    },

  ];
  const listDriverColumns = driverBaseColumns.concat([
    {
      title: '出库单号',
      dataIndex: 'number',
    },
    {
      title: '入库状态',
      dataIndex: 'confirm',
      valueEnum: {
        false: {
          text: '未确认',
          status: 'Error',
        },
        true: {
          text: '已确认',
          status: 'Success',
        },
      },
    },
    {
      title: '付款状态',
      dataIndex: 'status',
      valueEnum: {
        0: {
          text: '未付款',
          status: 'Error',
        },
        1: {
          text: '审批中',
          status: 'Error',
        },
        2: {
          text: '已付款',
          status: 'Success',
        },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      render: (_, item) => {
        return (
          <>
            <div style={{
              display: "flex",
              overflow: "hidden"
            }}>
              {
                (item.id !== '0' && !item.confirm)?(<>
                  <Access accessKey={"@stuff_revoke"}>
                    <Button
                      type="primary"
                      danger
                      style={{
                        marginLeft: "10px"
                      }}
                      onClick={() => {
                        Modal.confirm({
                          title: '注意',
                          content: '确定要撤销此承运信息?',
                          onOk() {
                            let id = item.id;
                            delDriver({
                              id
                            }).then(res => {
                              if (res?.code === 0) {
                                message.info("撤销成功");
                              }
                              actionRef.current.reload();
                            })

                          },
                          onCancel() {},
                        });
                      }}
                    >
                      撤回
                    </Button>
                  </Access>

                </>):(<></>)
              }
              {
                (item.id !== '0' && item.confirm && item.status === 0)?(<>
                  <Access accessKey={"@stuff_changeMoney"}>
                    <Button
                      type="primary"
                      danger
                      style={{
                        marginLeft: "10px"
                      }}
                      onClick={() => {
                        let payMoney = item.carMoney;
                        Modal.info({
                          title: '请确认付款金额',
                          okText:'提交',
                          closable:true,
                          content: (
                            <>
                              <div>
                                <Input placeholder="修改运费金额" defaultValue={payMoney} onChange={(e) => {
                                  payMoney = e.target.value;
                                }}/>
                              </div>
                            </>
                          ),
                          onOk() {
                            changeMoney({
                              id: item.id,
                              carMoney:payMoney
                            }).then(res => {
                              message.info("已发起付款申请");
                              actionRef.current.reload();
                            })
                          },
                        });
                      }}
                    >
                      申请付款
                    </Button>
                  </Access>

                </>):(<></>)
              }
            </div>
          </>
        )
      }
    }
  ]);
  const addDriverColumns = driverBaseColumns.concat([
    {
      title: '备注',
      dataIndex: 'remake',
      valueType: 'text',
    },
    {
      title: '附件',
      dataIndex: 'option',
      renderFormItem: () => {
        return (
          <Upload
            name="file"
            action={() => {
              return `${baseUrl}supplyChain/stuff/inStockFile`;
            }}
            listType="picture-card"
            defaultFileList={fileList}
            onChange={handlePayUploadChange}
            onRemove={handleRemove}
            data={{stuffId: record.id}}
            headers={{token: sessionStorage.getItem('token'), type: 'ADMIN'}}
          >
            {fileList.length >= 5 ? null : (
              <div>
                <PlusOutlined/>
                <div style={{marginTop: 8}}>入库单据</div>
              </div>
            )}
          </Upload>
        );
      },
    }
  ]);
  const orderDetailColumns = detailShowColumns.concat([
    {
      title: '入库数量',
      dataIndex: 'driverStock',
      hideInSearch: true,
    },

  ]);
  const goodsDetailRender = (e) => {
    return <>
      <ProTable
        rowKey={r => r.id}
        scroll={{x: 1400}}
        bordered
        dataSource={e.goodsDetails}
        search={false}
        toolBarRender={false}
        pagination={false}
        columns={orderDetailColumns}
      />
    </>
  };
  const driverDetailRender = (e) => {
    return <ProTable
      rowKey={r => r.id}
      scroll={{x: 1400}}
      bordered
      dataSource={e.drivers}
      search={false}
      toolBarRender={false}
      pagination={false}
      columns={listDriverColumns}
      expandedRowRender={goodsDetailRender}
    />;
  };

  const handlePayUploadChange = (info) => {
    if (info.file.status === 'uploading') {
      return;
    }
    if (info.file.status === 'error') {
      message.error("文件上传失败");
      return;
    }
    if (info.file.status === 'removed'){
      handleFileList(fileList.filter(file=>file.uid !== info.file.uid));
      return;
    }
    if (info.file.status === 'done'){
      fileList.push({
        uid:info.file.response.data.id,
        status: 'done',
        url:info.file.response.data.img
      });
      handleFileList(fileList);
    }
  };
  const handleRemove = (file)=>{
    let id =  file.response?file.response?.data.id:file.uid;
    if (!id){
      message.error("未上传完成,稍后再试!");
      return ;
    }
    return delPayFile({
      id
    }).then((res)=>{})
  };

  return (
    <PageContainer>
      <ProTable
        headerTitle="订单列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        scroll={{x: 1400}}
        bordered
        request={(params, sorter, filter) => purchaseList({...params, sorter, filter})}
        postData={(payload) => {
          const {list, total} = payload;
          setCount(total);
          return list || [];
        }}
        toolBarRender={() => [

        ]}
        columns={columns}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: false,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
        expandedRowRender={driverDetailRender}
      />

      <CreateForm width={1300} onCancel={() => handlePurchaseDetail(false)} modalVisible={purchaseDetail}
                  btn_view={false}>
        <div style={{width: '100%', height: '100%'}}>
          <Divider orientation="left">订单详情</Divider>
          <ProTable
            headerTitle="详情列表"
            rowKey="barCode"
            scroll={{x: 1400}}
            bordered
            dataSource={details.details}
            search={false}
            toolBarRender={false}
            pagination={false}
            columns={detailShowColumns}
          />
          <Divider orientation="left">采购合同</Divider>
          <Upload
            defaultFileList={
              details.imgs?.map(img => {
                let filename = img.img;
                filename = filename.substring(filename.lastIndexOf("/")+1);
                return {
                  uid: img.id,
                  name: filename,
                  status: 'done',
                  url: img.img,
                }
              })
            }
          showUploadList = {
            {
              showDownloadIcon: true,
              downloadIcon: '下载文件',
              showRemoveIcon: false,
            }
          }
          >
          </Upload>
          {
            (
            record.status === 9 ? (<>
              <Divider orientation="left">收货凭证</Divider>
              <Image.PreviewGroup>
                {
                  details.payImgs?.map(img => {
                    return <Image key={img.id} width={100} height={100} src={img.img}/>
                  })
                }
              </Image.PreviewGroup>
            </>): null
            )
          }
        </div>
      </CreateForm>
      <CreateForm
        width={1300}
        onCancel={() => handlePurchaseDetails(false)}
        modalVisible={purchaseDetails}
        btn_view={false}
      >
        <div style={{width: '100%', height: '100%'}}>
          <Divider orientation="left">入库明细</Divider>
          <ProTable
            rowKey="key"
            scroll={{x: 1400}}
            bordered
            dataSource={details.details}
            search={false}
            toolBarRender={false}
            pagination={false}
            columns={detailColumns}
          />
          <Divider orientation="left">入库单据</Divider>
        </div>
      </CreateForm>
      <CreateForm
        width={1300}
        onCancel={() => handlePurchaseOutDetail(false)}
        modalVisible={purchaseOutDetail}
        btn_view={false}
      >
        <div style={{width: '100%', height: '100%'}}>
          <Divider orientation="left">入库明细</Divider>
          <div>
            <ProTable
              rowKey={r => r.id}
              scroll={{x: 540}}
              bordered
              dataSource={details.details}
              search={false}
              toolBarRender={false}
              pagination={false}
              columns={detailColumns}
              rowSelection={{
                fixed: true,
                selectedRowKeys: mySelectedRowKeys,
                onSelect, //用户手动选择/取消选择某行的回调
                onSelectMultiple: onMulSelect, //用户使用键盘 shift 选择多行的回调
                onSelectAll: onMulSelect, //用户手动选择/取消选择所有行的回调
                onChange, //选中项发生变化时的回调
                getCheckboxProps: record => {
                  return {
                    disabled: false
                  };
                },
              }}
              tableAlertRender={false}
              tableAlertOptionRender={false}
            />
          </div>
          <Divider orientation="left">车辆运费</Divider>
          <div>
            <ProTable
              className={styles.formModal}
              rowKey="id"
              bordered
              type="form"
              loading={driverStockLoading}
              onSubmit={(value) => {
                handleDriverStockLoading(true);
                if (mySelectedRowKeys.length > 0) {
                  let driverDetails = [];
                  details.details.filter(data=>mySelectedRowKeys.includes(data.id)).forEach(detail=>{
                    driverDetails.push({
                      detailId:detail.id,
                      outStock:detail.tempStock ? detail.tempStock : detail.value - detail.inStock
                    })
                  });

                  let params = Object.assign(value, {details: driverDetails, id: record.id});
                  addDriverDetails(params).then(res => {
                    handleDriverStockLoading(false);
                    if (res?.code === 0) {
                      message.success("添加成功!");
                      handlePurchaseOutDetail(false);
                      actionRef.current.reload();
                    }
                  })
                }else{
                  message.error("请选择入库明细!")
                }
              }}
              form={{
                layout: 'horizontal ',
                labelAlign: 'rihgt',
                labelCol: {span: 4},
                wrapperCol: {span: 12},
              }}
              columns={addDriverColumns}
            />
          </div>
        </div>
      </CreateForm>

    </PageContainer>
  );
};

export default TableList;
